<?php
defined('BASEPATH') or die('No direct script access allowed');
/**
 * 配置文件操作类
 * @Author gml
 * create 2015-11-2 17:30:10
 * $iniObj = new fileini('clouduser.ini');
 * $infoArr = $iniObj -> readini();
 * $newinfoArr = array('user1' => array('cid' => '1020420'));
 * $iniObj -> setini($newinfoArr);
 */
class fileini{
    private $file;
    private $handle = null;

    public function __construct($filename = null) {
        if( empty($filename) ) {
            $filename = 'fltconfig.dat';
        }
        $this -> file = $filename;
    }

    public function setini($info) {
        $this -> open();
        $inistr = '';
        if(is_array($info) && !empty($info)) {
            foreach($info as $key => $value) {

                if(is_array($value)) {
                    $inistr .= '['.$key.']'.PHP_EOL;
                    foreach($value as $ikey => $item) {
                        $inistr .= $ikey .'='. $item . PHP_EOL;
                    }
                } else {
                    $inistr .= $key .'='. $value . PHP_EOL;
                }
            }
        }

        if(!empty($inistr) && $this -> handle) {
            //先清空原来配置文件的内容
            ftruncate($this -> handle, 0);
            rewind($this -> handle); // 倒回文件指针的位置
            fwrite($this -> handle,$inistr);
            $this -> close();
        }
    }

    public function readini() {
        $this -> open();
        $return = array();
        if(!$this -> handle) {
            return $return;
        } else {
            $return = parse_ini_file($this -> file, true);
            $this -> close();
        }

        return $return;
    }

    public function open() {
        if(!file_exists($this -> file)) {
            $this -> handle = fopen($this -> file, 'w+');
        } else {
            $this -> handle = fopen($this -> file, 'r+');
        }

        flock($this -> handle,LOCK_EX);
    }

    public function close() {
        flock($this -> handle,LOCK_UN);
        fclose($this -> handle);
    }

}
?>